package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by yyc on 2016/8/3.
 */
public abstract class WLXBaseActivity extends AppCompatActivity {
    /** 记录处于前台的Activity */
    private static WLXBaseActivity mForegroundActivity = null;

    /** 记录所有活动的Activity */
    private static final List<WLXBaseActivity> mActivities = new LinkedList<WLXBaseActivity>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        mForegroundActivity = this;
        super.onResume();
    }

    @Override
    protected void onPause() {
        mForegroundActivity = null;
        super.onPause();
    }

//    public abstract void init();

    /** 关闭所有Activity */
    public static void finishAll() {
        List<WLXBaseActivity> copy;
        synchronized (mActivities) {
            copy = new ArrayList<WLXBaseActivity>(mActivities);
        }
        for (WLXBaseActivity activity : copy) {
            activity.finish();
        }
    }

    /** 关闭所有Activity，除了参数传递的Activity */
    public static void finishAll(WLXBaseActivity except) {
        List<WLXBaseActivity> copy;
        synchronized (mActivities) {
            copy = new ArrayList<WLXBaseActivity>(mActivities);
        }
        for (WLXBaseActivity activity : copy) {
            if (activity != except) activity.finish();
        }
    }

    /** 是否有启动的Activity */
    public static boolean hasActivity() {
        return mActivities.size() > 0;
    }

    /** 获取当前处于前台的activity */
    public static WLXBaseActivity getForegroundActivity() {
        return mForegroundActivity;
    }

    /** 获取当前处于栈顶的activity，无论其是否处于前台 */
    public static WLXBaseActivity getCurrentActivity() {
        List<WLXBaseActivity> copy;
        synchronized (mActivities) {
            copy = new ArrayList<WLXBaseActivity>(mActivities);
        }
        if (copy.size() > 0) {
            return copy.get(copy.size() - 1);
        }
        return null;
    }

    /** 退出应用 */
    public void exitApp() {
        finishAll();
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
     * 打开一个Activity 默认 不关闭当前activity
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, false, null);
    }

    public void startActivity(Class<?> clz,boolean isCloseCurrentActivity) {
        startActivity(clz, isCloseCurrentActivity, null);
    }

    public  void startActivity(Class<?> clz,boolean isCloseCurrentActivity,Bundle ex) {
        Intent intent=new Intent(this, clz);
        if(ex!=null)
            intent.putExtras(ex);
        startActivity(intent);
        if (isCloseCurrentActivity) {
            finish();
        }
    }
}
